package com.example.tranhtheuchuthap;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Bitmap.CompressFormat;
import android.text.format.DateFormat;
import android.util.FloatMath;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Tranhtheu extends Activity implements OnTouchListener{
	// These matrices will be used to move and zoom image
	   Matrix matrix = new Matrix();
	   Matrix savedMatrix = new Matrix();

	   // We can be in one of these 3 states
	   static final int NONE = 0;
	   static final int DRAG = 1;
	   static final int ZOOM = 2;
	   int mode = NONE;

	   // Remember some things for zooming
	   PointF start = new PointF();
	   PointF mid = new PointF();
	   float oldDist = 1f;
	
	   //end them
	   
	 private static final String TAG = Tranhtheu.class.getName();
	   private static final String FILENAME = "myFile.txt";
	   private boolean fullsize = false;
	   String filePath="";
	Button btnChonAnh,btnTuyChon;
	ImageView imageview;
	Bitmap resize_image=null,full_image=null,photo=null;
	
	
	String somau="",chieudai="",chieucao="",dokho="";

	String url_IP="http://prtg.techlinkvn.com/crossstitch";
	private static int REQ_CODE_HIEUCHINH = 101,REQ_CAMERA=0,REQ_GALLERY=1,REQ_CHONANH=102,
			REQ_TUYCHON=103;
	private long lastPressTime=0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tranhtheu);
		
		 btnChonAnh = (Button) findViewById(R.id.id_chonanh);
		 btnTuyChon=(Button)findViewById(R.id.id_tuychon);
		 imageview=(ImageView)findViewById(R.id.id_imageview);
		 imageview.setOnTouchListener(this);
		 try{
	
			 imageview.setOnClickListener(new View.OnClickListener() {
			 
			   @Override
			   public void onClick(View v) {    
				   long pressTime = System.currentTimeMillis();
				   if(pressTime-lastPressTime<250){			
					 /*  if(!filePath.equals("")){
						   Intent i = new Intent(getApplicationContext(), Full_Image.class);
							
							i.putExtra("path", filePath);
							startActivity(i);  

					   }*/
					   if(fullsize){
						   try{
					   imageview.setImageBitmap(full_image);
						   }catch(OutOfMemoryError out){
							     Toast.makeText(getApplicationContext(),
							                "Kích thước ảnh quá lớn!", Toast.LENGTH_LONG).show();    
						 }
					   fullsize=false;
					   }
					   else{
						   imageview.setImageBitmap(resize_image);
						   fullsize=true;
					   }
				   }
			      else lastPressTime=pressTime;
			   }        
			});
		
		 }
		 catch(Exception e){
			 writeToFile(FILENAME, "error click imageview");
		 }
	   catch(OutOfMemoryError oome){
		   writeToFile(FILENAME, "out of memory when click imageview");
	   }
	   catch(Throwable t){
		   writeToFile(FILENAME, "error throwable");
	   }
		 //button click
		
		btnChonAnh.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		    	Intent i = new Intent(getApplicationContext(), Chon_Anh.class);
				startActivityForResult(i, REQ_CHONANH);
				}

		});
		
		//code
		
		btnTuyChon.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		    	Intent i = new Intent(getApplicationContext(), Tuy_Chon.class);
				startActivityForResult(i, REQ_TUYCHON);
		    	
				}

		});
		
	
	}
	//them
	 @Override
	   public boolean onTouch(View v, MotionEvent event) {
	      ImageView view = (ImageView) v;

	      // Dump touch event to log
	      dumpEvent(event);

	      // Handle touch events here...
	      switch (event.getAction() & MotionEvent.ACTION_MASK) {
	      case MotionEvent.ACTION_DOWN:
	         savedMatrix.set(matrix);
	         start.set(event.getX(), event.getY());
	         Log.d(TAG, "mode=DRAG");
	         mode = DRAG;
	         break;
	      case MotionEvent.ACTION_POINTER_DOWN:
	         oldDist = spacing(event);
	         Log.d(TAG, "oldDist=" + oldDist);
	         if (oldDist > 10f) {
	            savedMatrix.set(matrix);
	            midPoint(mid, event);
	            mode = ZOOM;
	            Log.d(TAG, "mode=ZOOM");
	         }
	         break;
	      case MotionEvent.ACTION_UP:
	      case MotionEvent.ACTION_POINTER_UP:
	         mode = NONE;
	         Log.d(TAG, "mode=NONE");
	         break;
	      case MotionEvent.ACTION_MOVE:
	         if (mode == DRAG) {
	            // ...
	            matrix.set(savedMatrix);
	            matrix.postTranslate(event.getX() - start.x,
	                  event.getY() - start.y);
	         }
	         else if (mode == ZOOM) {
	            float newDist = spacing(event);
	            Log.d(TAG, "newDist=" + newDist);
	            if (newDist > 10f) {
	               matrix.set(savedMatrix);
	               float scale = newDist / oldDist;
	               matrix.postScale(scale, scale, mid.x, mid.y);
	            }
	         }
	         break;
	      }

	      view.setImageMatrix(matrix);
	      return true; // indicate event was handled
	   }

	   /** Show an event in the LogCat view, for debugging */
	   private void dumpEvent(MotionEvent event) {
	      String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
	            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
	      StringBuilder sb = new StringBuilder();
	      int action = event.getAction();
	      int actionCode = action & MotionEvent.ACTION_MASK;
	      sb.append("event ACTION_").append(names[actionCode]);
	      if (actionCode == MotionEvent.ACTION_POINTER_DOWN
	            || actionCode == MotionEvent.ACTION_POINTER_UP) {
	         sb.append("(pid ").append(
	               action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
	         sb.append(")");
	      }
	      sb.append("[");
	      for (int i = 0; i < event.getPointerCount(); i++) {
	         sb.append("#").append(i);
	         sb.append("(pid ").append(event.getPointerId(i));
	         sb.append(")=").append((int) event.getX(i));
	         sb.append(",").append((int) event.getY(i));
	         if (i + 1 < event.getPointerCount())
	            sb.append(";");
	      }
	      sb.append("]");
	      Log.d(TAG, sb.toString());
	   }

	   /** Determine the space between the first two fingers */
	   private float spacing(MotionEvent event) {
	      float x = event.getX(0) - event.getX(1);
	      float y = event.getY(0) - event.getY(1);
	      return FloatMath.sqrt(x * x + y * y);
	   }

	   /** Calculate the mid point of the first two fingers */
	   private void midPoint(PointF point, MotionEvent event) {
	      float x = event.getX(0) + event.getX(1);
	      float y = event.getY(0) + event.getY(1);
	      point.set(x / 2, y / 2);
	   }
	   
	   @Override
		protected void onDestroy() {
			// TODO Auto-generated method stub
			super.onDestroy();
		}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == REQ_CAMERA && resultCode == RESULT_OK) {  
			File f = new File(Environment.getExternalStorageDirectory()
					.toString());
			for (File temp : f.listFiles()) {
				if (temp.getName().equals("temp.jpg")) {
					f = temp;
					break;
				}
			}
			try {
				
				BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

				photo = BitmapFactory.decodeFile(f.getAbsolutePath(),
						btmapOptions);

				

				String path = android.os.Environment
						.getExternalStorageDirectory()
						+ File.separator
						+ "Phoenix" + File.separator + "default";
				f.delete();
				OutputStream fOut = null;
				File file = new File(path, String.valueOf(System
						.currentTimeMillis()) + ".jpg");
				try {
					fOut = new FileOutputStream(file);
					photo.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
					fOut.flush();
					fOut.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			resize_image=photo;
			full_image=photo;
            imageview.setImageBitmap(resize_image);
            saveImage(photo, "photo");
            filePath="/mnt/sdcard/photo.png";
        }
        else if (requestCode == REQ_GALLERY) {
        	try {
			Uri selectedImageUri = data.getData();

			String tempPath = getPath(selectedImageUri, Tranhtheu.this);
			writeToFile(FILENAME, tempPath);
			filePath=tempPath;
			photo = decodeSampledBitmapFromFile(tempPath, 200, 200);
        		
			imageview.setImageBitmap(photo);
        	}catch(Exception e){
        		 Toast.makeText(getApplicationContext(),
			                "Kích thước ảnh quá lớn!", Toast.LENGTH_LONG).show();
			    
        	}
		}
        else if(requestCode==REQ_CODE_HIEUCHINH && resultCode==RESULT_OK){
        	 
 				somau=data.getStringExtra("somau");
 				chieudai=data.getStringExtra("chieudai");
 				chieucao=data.getStringExtra("chieucao");
 				dokho=data.getStringExtra("dokho");
 				new dataUpload().execute("thamso");
        }
 				else if(requestCode==REQ_CHONANH && resultCode==RESULT_OK){
 					if(data.getExtras().getInt("key")==1){
 						Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 						File f = new File(android.os.Environment
 								.getExternalStorageDirectory(), "temp.jpg");
 						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
 						startActivityForResult(intent, REQ_CAMERA);
 					}
 					if(data.getExtras().getInt("key")==2){
 						try{
							Intent intent = new Intent(
									Intent.ACTION_PICK,
									android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
							intent.setType("image/*");
							
							startActivityForResult(
									Intent.createChooser(intent, "Select File"),
									REQ_GALLERY);
							}
							catch(RuntimeException e){
								
							}
							catch(Exception e){
							
							}
 					}
 				}
 		
 				else if(requestCode==REQ_TUYCHON && resultCode==RESULT_OK){
 					if(data.getExtras().getInt("key")==1){
 						new dataUpload().execute("guianh");
 					}
 					if(data.getExtras().getInt("key")==2){
 						Intent i = new Intent(getApplicationContext(), HieuChinh.class);
					startActivityForResult(i, REQ_CODE_HIEUCHINH);
 					}
 					if(data.getExtras().getInt("key")==3){
 						Intent i = new Intent(getApplicationContext(), TraBangMau.class);
						startActivity(i);
 					}
 					if(data.getExtras().getInt("key")==4){
 						AlertDialog.Builder editalert = new AlertDialog.Builder(Tranhtheu.this);

						editalert.setTitle("LƯU ẢNH");
						editalert.setMessage("Tên ảnh");


						final EditText input = new EditText(Tranhtheu.this);
						
						input.setHeight(100);
						input.setWidth(200);
						input.setHint("nhập tên ");
						editalert.setView(input);

						editalert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						    public void onClick(DialogInterface dialog, int whichButton) {

						    	saveImage(photo,input.getText().toString());
						    }
						});


						editalert.show();
						
 					}
 					if(data.getExtras().getInt("key")==5){
 						 AlertDialog.Builder builder1 = new AlertDialog.Builder(Tranhtheu.this);
				           
				            builder1.setCancelable(true);
				            builder1.setPositiveButton("view",
				                    new DialogInterface.OnClickListener() {
				                public void onClick(DialogInterface dialog, int id) {
				                	String strlog=readFromFile(FILENAME);
									 Intent myIntent = new Intent(Tranhtheu.this, Showlog.class);
									 myIntent.putExtra("key", strlog); 
									 Tranhtheu.this.startActivity(myIntent);
				                }
				            });
				            builder1.setNegativeButton("Clear",
				                    new DialogInterface.OnClickListener() {
				                public void onClick(DialogInterface dialog, int id) {
				                	try {
				           	    	 
				         	           OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_PRIVATE));
				         	          
				         	           
				         	           outputStreamWriter.close();
				         	    	   
				         	       }
				         	       catch (IOException e) {
				         	           Log.e(TAG, "File write failed: " + e.toString());
				         	       } 
				                	dialog.cancel();
				                }
				            });

				            AlertDialog alert11 = builder1.create();
				            alert11.show();
 					}
 					
 				}
	}//end OnActivityResult
	public String getPath(Uri uri, Activity activity) {
		String[] projection = { MediaColumns.DATA };
		Cursor cursor = activity
				.managedQuery(uri, projection, null, null, null);
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}//end getPath
	private String uploadImage(Bitmap bitmap)
    {
    	try
    	{
    		//List<NameValuePair> nameValuePairs = new java.util.ArrayList<NameValuePair>();
    		 HttpClient httpClient = new DefaultHttpClient();
    		 HttpContext localContext = new BasicHttpContext();
    		 HttpPost httpPost = new HttpPost(url_IP+"/uploadImage/upload_file.php");
    		 
    		 MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    		 
    		 Bitmap bm=getResizedBitmap(bitmap, 640,480);
    		 ByteArrayOutputStream bos = new ByteArrayOutputStream();
    		 bm.compress(CompressFormat.JPEG, 100, bos);
    		 byte[] data = bos.toByteArray();
    		 entity.addPart("photoId",new StringBody("123"));
    		 entity.addPart("uploaded", new ByteArrayBody(data,"myImage.jpg"));
    		 //entity.addPart("file",new FileBody(new File))
    		 httpPost.setEntity(entity);
    		 HttpResponse response = httpClient.execute(httpPost, localContext);
    		 writeToFile(FILENAME,"da upload image");
    		 BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8"));               
    		  String sResponse = reader.readLine();
    		 return sResponse;

    	}
    	catch (Exception e)
    	{
    		System.out.print("error");
    		writeToFile(FILENAME, "chua nhan duoc response");
    	}
		return "error";
    	
    
    }
	public String guiHieuChinh(){
		try
		{
			//List<NameValuePair> nameValuePairs = new java.util.ArrayList<NameValuePair>();
			 HttpClient httpClient = new DefaultHttpClient();
			 HttpContext localContext = new BasicHttpContext();
			 HttpPost httpPost = new HttpPost(url_IP+"/uploadImage/upload_parameter.php");
			 String cookies=DeviceInfomation.getDeviceName()+"&"+DeviceInfomation.getDeviceId()+"&"
			 +String.valueOf(System.currentTimeMillis());
			 MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("SoMau",new StringBody(somau));
			 entity.addPart("ChieuCao",new StringBody(chieucao));
			 entity.addPart("ChieuDai",new StringBody(chieudai));
			 entity.addPart("DoKho",new StringBody(dokho));
			 entity.addPart("cookie",new StringBody(cookies));
			writeToFile(FILENAME, cookies);
			 httpPost.setEntity(entity);
			 HttpResponse response = httpClient.execute(httpPost, localContext);
			
			 BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8"));               
			  String sResponse = reader.readLine();
			  
			 return sResponse;

		}
		catch (Exception e)
		{
			writeToFile(FILENAME, "error click gui hieu chinh");
		}
		return"error";
	}
	public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();
        float bitmapRatio = width / height;
        if(width>maxSize||height>maxSize){
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
}
	public Bitmap getResizedBitmap(Bitmap image, int w, int h) {
		int width = image.getWidth();
        int height = image.getHeight();
        
        if(width<w||height<h){
        	if(width<w){
        		w=width;
        	}
        	if(height<h){
        		h=height;
        	}
        }
        return Bitmap.createScaledBitmap(image, w, h, true);
}
	public void saveImage(  Bitmap myBitmap,String name) {
		
		    File sdCardDirectory = Environment.getExternalStorageDirectory();
			   
		     final File file = new File(sdCardDirectory, name+".png");
		    if (file.exists ()) {
                                file.delete();
						      
		    }
		    else
		    {
		    	 try {
    		           FileOutputStream out = new FileOutputStream(file);
    		           myBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
    		           out.flush();
    		           out.close();

    		    } catch (Exception e) {
    		           e.printStackTrace();
    		    }
		    	 
		    }
	}
	public void hienThiAnh(Bitmap bm){
		resize_image=getResizedBitmap(bm, 640);
		full_image=bm;
		imageview.setImageBitmap(resize_image);
	}
public void writeToFile(String filename,String data) {
	       try {
	    	   Date d = new Date();
	           CharSequence s  = DateFormat.format("yyyy-MM-dd hh:mm:ss: ", d.getTime());
	       
	    	  
	           OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(filename, Context.MODE_APPEND));
	           outputStreamWriter.write(s+data+"\n");
	           
	           outputStreamWriter.close();
	    	   
	       }
	       catch (IOException e) {
	           Log.e(TAG, "File write failed: " + e.toString());
	       } 
	        
	   }
   public String readFromFile(String filename) {
	        
	       String ret = "";
	        
	       try {
	           InputStream inputStream = openFileInput(filename);
	            
	           if ( inputStream != null ) {
	               InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
	               BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
	               String receiveString = "";
	               StringBuilder stringBuilder = new StringBuilder();
	                
	               while ( (receiveString = bufferedReader.readLine()) != null ) {
	                   stringBuilder.append(receiveString);
	                   stringBuilder.append("\n");
	               }
	                
	               inputStream.close();
	               ret = stringBuilder.toString();
	           }
	       }
	       catch (FileNotFoundException e) {
	           Log.e(TAG, "File not found: " + e.toString());
	       } catch (IOException e) {
	           Log.e(TAG, "Can not read file: " + e.toString());
	       }

	       return ret;
	   }
	   public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 
			// Raw height and width of image    
			final int height = options.outHeight;    
			final int width = options.outWidth;    
			int inSampleSize = 1;    
			if (height > reqHeight || width > reqWidth) {       
				// Calculate ratios of height and width to requested height and width      
				final int heightRatio = Math.round((float) height / (float) reqHeight);     
				final int widthRatio = Math.round((float) width / (float) reqWidth);      
				// Choose the smallest ratio as inSampleSize value, this will guarantee      
				// a final image with both dimensions larger than or equal to the        
				// requested height and width.       
				inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;    } 
			return inSampleSize;
			}
		public static Bitmap decodeSampledBitmapFromFile(String res,int reqWidth, int reqHeight) { 
			// First decode with inJustDecodeBounds=true to check dimensions   
			final BitmapFactory.Options options = new BitmapFactory.Options();  
			options.inJustDecodeBounds = true;  
			BitmapFactory.decodeFile(res, options);   
			// Calculate inSampleSize   
			options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 
			// Decode bitmap with inSampleSize set  
			options.inJustDecodeBounds = false;  
			
			return BitmapFactory.decodeFile(res, options);	
			
		}
		public static void CopyStream(InputStream is, OutputStream os) {
		    final int buffer_size = 1024;
		    try {
		      byte[] bytes = new byte[buffer_size];
		      for (;;) {
		        int count = is.read(bytes, 0, buffer_size);
		        if (count == -1)
		          break;
		        os.write(bytes, 0, count);
		      }
		    } catch (Exception ex) {
		    }
		  }

		/*private Bitmap getBitmap(String url) {
		    // from web
			
		    try {
		    	 File sdCardDirectory = Environment.getExternalStorageDirectory();
		    	final File file = new File(sdCardDirectory, "file.txt");
		    	if (file.exists ()) {
                    file.delete();
			      
}
		        Bitmap bitmap = null;
		        
		        InputStream input = new java.net.URL(url)
					.openStream();
		        try {
		            
		            final OutputStream output = new FileOutputStream(file);
		            try {
		                try {
		                    final byte[] buffer = new byte[1024];
		                    int read;

		                    while ((read = input.read(buffer)) != -1)
		                        output.write(buffer, 0, read);

		                    output.flush();
		                } finally {
		                    output.close();
		                }
		            } catch (Exception e) {
		                e.printStackTrace();
		            }
		        } finally {
		            input.close();
		        }
		      
		        
		        bitmap = decodeFile(file);
		        return bitmap;
		    } catch (Exception ex) {
		        ex.printStackTrace();
		        return null;
		    }
		}*/

		// decodes image and scales it to reduce memory consumption
		private Bitmap decodeFile(String res) {
		    try {
		        // decode image size
		        BitmapFactory.Options o = new BitmapFactory.Options();
		        o.inJustDecodeBounds = true;
		        BitmapFactory.decodeFile(res, o);

		        // Find the correct scale value. It should be the power of 2.
		        final int REQUIRED_SIZE = 150;
		        int width_tmp = o.outWidth, height_tmp = o.outHeight;
		        int scale = 1;
		        while (true) {
		            if (width_tmp / 2 < REQUIRED_SIZE
		                    || height_tmp / 2 < REQUIRED_SIZE)
		                break;
		            width_tmp /= 2;
		            height_tmp /= 2;
		            scale *= 2;
		        }

		        // decode with inSampleSize
		        BitmapFactory.Options o2 = new BitmapFactory.Options();
		        o2.inSampleSize = scale;
		        return BitmapFactory.decodeFile(res, o2);
		    } catch (Exception e) {
		    }
		    return null;
		}
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.tranhtheu, menu);
		return true;
		
		
		//A
		
	}
	public class dataUpload extends AsyncTask<String, Void, Bitmap> {
		
        @Override
        protected Bitmap doInBackground(String... param) {
        	Bitmap bm=null,bm1=null;
        	
           if(param[0]=="guianh"){
        	   
        	String str=uploadImage(photo);
        	
           }
           
           if(param[0]=="thamso"){
        	  
        	  String str=guiHieuChinh();
        	  
        	  writeToFile(FILENAME, str);
        	  
        	  
  	         
        	  try {
  				// Download Image from URL
        		 
//DownloadFromUrl(str, "image");
        		  
        		  
        		  
        		//bm1=getBitmap(str);
  				InputStream input = new java.net.URL(str)
  						.openStream();
  				bm = BitmapFactory.decodeStream(input);
  				photo=bm;
  				
  			} catch (Exception e) {
  				// Error Log
  				Log.e("Error", e.getMessage());
  				e.printStackTrace();
  				writeToFile(FILENAME, "error download image");
  			}
        	  catch(OutOfMemoryError oe){
        		  writeToFile(FILENAME, "out of memory when dowload image");
        		  
        	  }
           }
          
           
           
            return bm;
        }
        @Override
		protected void onPostExecute(Bitmap result) {
			// Set image into image.xml layout
			//photo=result;
        	
        	
        	
        	try{
			if(result!=null){
				//full_image=result;
				//resize_image=getResizedBitmap(result,640);
				//fullsize = true;
			//imageview.setImageBitmap(resize_image);
				//imageview.setImageBitmap(result);
				hienThiAnh(result);
			saveImage(result, "image");
			
			}
        	}
        	catch(Exception e){
        		writeToFile(FILENAME, "error hien thi anh download");
        	}
		}
        
        
	}
}
